<template>
  <el-card shadow="never">
    <template #header>
      <el-form label-width="80px">
        <el-row :gutter="24">
          <el-col :span="6" :xs="24">
            <el-form-item label="渠道名称">
              <el-select v-model="page.channelId" style="width: 100%" clearable>
                <el-option v-for="item in channelList" :key="item.id" :value="item.id"
                           :label="item.channelName"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
            <el-form-item label="最新交易时间" label-width="100px">
              <el-date-picker
                  style="width: 100%"
                  v-model="page.createTimeValue"
                  type="daterange"
                  range-separator="~"
                  value-format="x"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6" :xs="24">
            <el-form-item label-width="20px">
              <el-button type="primary" @click="getTableData">查询</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
    </template>
    <div style="margin-bottom: 10px;text-align: right">
      <el-button type="primary" icon="el-icon-plus" @click="downTemplate">下载模板</el-button>
      <el-button type="primary" @click="addChannelVisible = true">新增</el-button>
    </div>
    <Table :tableData="tableData" :tableColumn="tableColumn" :page="page"
           @handleCurrentChange="(val)=>{page.pageNum = val,getTableData()}"
           @handleSizeChange="(val)=>{page.pageSize = val,getTableData()}"
    >
      <template #handle="{row}">
        <el-button type="text" @click="addTransaction(row)">新增交易</el-button>
        <!--        <el-button type="text" @click="details(row)">明细</el-button>-->
      </template>
    </Table>
    <!--     新增渠道-->
    <Dialog title="新增渠道" v-model="addChannelVisible" @cancel="addChannelVisible = false" @confirm="addChannelConfirm"
            @close="addChannelClose">
      <el-form ref="addChannelFormRef" :model="addChannelForm" label-width="80px">
        <el-form-item label="渠道名称" prop="channelName" :rules="[
          {required:true,trigger: 'blur',message:'不能为空'}
        ]">
          <el-input v-model="addChannelForm.channelName"/>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input type="textarea" :rows="4" v-model="addChannelForm.remarks"/>
        </el-form-item>
      </el-form>
    </Dialog>

    <!--     新增交易-->
    <Dialog title="新增交易" v-model="addTransactionVisible" @close="clearTransactionForm"
            @cancel="addTransactionVisible = false"
            @confirm="addTransactionConfirm">
      <el-form ref="addTransactionFormRef" :model="addTransactionForm" label-width="80px"
               :rules="addTransactionRulesForm">
        <el-form-item label="渠道名称">
          <el-input :disabled="true" v-model="addTransactionForm.channelName"/>
        </el-form-item>
        <el-form-item label="单价" prop="unitPrice">
          <el-input v-model="addTransactionForm.unitPrice" oninput="value = value.replace(/[^\d.]/g, '');"/>
        </el-form-item>
        <el-form-item label="交易日期" prop="tradingTime">
          <el-date-picker
              v-model="addTransactionForm.tradingTime"
              value-format="YYYY-MM-DD "
              type="date"
          />
        </el-form-item>
        <el-form-item label="导入名单" prop="file">
          <el-upload
              ref="uploadFileRef"
              :http-request="uploadFile"
              :limit="1"
              action="#"
              :on-remove="onRemove"
              :before-upload="beforeUpload"
              accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          >
            <el-button type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
    </Dialog>

    <Dialog v-model="detailsVisible" title="明细" :footer="false" width="60%" @close="detailsPageClear">
      <el-form>
        <el-row :gutter="24">
          <el-col :span="12" :xs="24">
            <el-form-item label="交易时间" label-width="80px">
              <el-date-picker
                  style="width: 100%"
                  v-model="detailsPage.createTimeValue"
                  type="daterange"
                  range-separator="~"
                  value-format="x"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
            <el-form-item>
              <el-button type="primary" @click="getTransactionDetails">查询</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <Table :table-column="detailsTableColumn" :tableData="detailsTableData" :page="detailsPage"
             @handleCurrentChange="(val)=>{detailsPage.pageNum = val,getTransactionDetails()}"
             @handleSizeChange="(val)=>{detailsPage.pageSize = val,getTransactionDetails()}"
      >
        <template #unitPrice="{row}">
          <el-input v-if="priceKey === row.tradingId" v-model="row.unitPrice"
                    oninput="value = value.replace(/[^\d.]/g, '');"/>
          <span v-else>{{ row.unitPrice }}</span>
        </template>
        <template #handle="{row}">
          <el-button type="text" v-if="priceKey !== row.tradingId" @click="priceKey = row.tradingId">修改单价</el-button>
          <el-button type="text" v-else @click="savePrice(row)" style="color: #e6a23c">保存</el-button>
        </template>
      </Table>
    </Dialog>
  </el-card>
</template>

<script>
import {defineComponent, onMounted, reactive, ref, toRefs,} from 'vue'
import {
  fetchChannelNameList,
  addChannel,
  selectChannel,
  addChannelTrading,
  channelTradingEditUnitPrice,
  fetchChannelTrading
} from '@/api/channel'
import {dateFormatTimeStamp} from "@/utils";
import {ElMessage, ElMessageBox} from "element-plus";

const tableColumn = [
  {label: '渠道名称', prop: 'channelName', align: 'center'},
  {label: '最新交易时间', prop: 'tradingTime', align: 'center'},
  {label: '创建人', prop: 'systemUserName', align: 'center'},
  {label: '新建时间', prop: 'creationTime', align: 'center'},
  {label: '备注', prop: 'remarks', align: 'center'},
  {label: '操作', slot: 'handle', align: 'center'},
]
const detailsTableColumn = [
  {label: '交易时间', prop: 'tradingTime', align: 'center'},
  {label: '名单数', prop: 'orderNum', align: 'center'},
  {label: '单价', prop: 'unitPrice', slot: 'unitPrice', align: 'center'},
  {label: '操作', slot: 'handle', align: 'center'},
]
export default {
  name: "Channel",
  setup() {
    const addChannelFormRef = ref(null)
    const addTransactionFormRef = ref(null)
    const uploadFileRef = ref(null)
    const state = reactive({
      page: {
        pageSize: 10,
        pageNum: 1,
        total: 0
      },
      channelList: [],
      tableData: [],
      addChannelVisible: false,
      addChannelForm: {
        channelName: null,
        remarks: null
      },
      addTransactionVisible: false,
      detailsRows: {},
      priceKey: null,
      detailsPage: {
        pageSize: 10,
        pageNum: 1,
        total: 0
      },
      detailsTableData: [],
      addTransactionForm: {
        unitPrice: null,
        tradingTime: null,
        file: null
      },
      addTransactionRulesForm: {
        unitPrice: {
          required: true, message: '不能为空'
        },
        tradingTime: {
          required: true, message: '请选择日期', trigger: 'change', type: 'date'
        },
        file: {
          required: true, message: '请选择文件', trigger: 'change',
        }
      },
      detailsVisible: false
    })
    const methods = {
      async getTableData() {
        const [datetimeStart, datetimeEnd] = dateFormatTimeStamp(state.page.createTimeValue)
        const params = {
          datetimeStart, datetimeEnd,
          ...state.page,
          createTimeValue: null
        }
        const res = await fetchChannelNameList(params)
        if (res.code === 200) {
          const {list, total} = res.data
          state.tableData = list
          state.page.total = total
        }
      },
      resetSearch() {
        state.page = {
          pageSize: 10,
          pageNum: 1,
          total: 0
        }
        state.getTableData()
      },
      addChannelClose() {
        addChannelFormRef.value.resetFields()
      },
      getSelect() {
        selectChannel().then(res => {
          state.channelList = res.data
        })
      },
      addTransaction(row) {
        state.addTransactionVisible = true
        state.addTransactionForm = {
          ...row,
          channelName: row.channelName,
          unitPrice: row.unitPrice || null,
          tradingTime: null
        }
      },
      beforeUpload(file) {
        state.addTransactionForm.file = file
      },
      onRemove() {
        state.addTransactionForm.file = null
      },
      uploadFile() {
      },
      downTemplate() {
        const a = document.createElement('a')
        a.href = 'https://mx-yundun.oss-us-east-1.aliyuncs.com/file/Data_user_%20template.xlsx'
        a.click()

      },
      addTransactionConfirm() {
        addTransactionFormRef.value.validate(async v => {
          if (v) {
            const formData = new FormData()
            const {unitPrice, tradingTime, file, id} = state.addTransactionForm
            formData.append('unitPrice', unitPrice)
            formData.append('tradingTime', tradingTime)
            formData.append('channelId', id)
            formData.append('file', file)
            const res = await addChannelTrading(formData)
            if (res.code === 200) {
              ElMessage({
                message: res.message,
                type: 'success',
                duration: 5000
              })
              methods.getTableData()
              state.addTransactionVisible = false
            }
          }
        })
      },
      clearTransactionForm() {
        uploadFileRef.value.clearFiles()
        addTransactionFormRef.value.resetFields()
      },
      async details(rows) {
        state.detailsRows = {...rows}
        await methods.getTransactionDetails()
        state.detailsVisible = true
      },
      async getTransactionDetails() {
        const [datetimeStart, datetimeEnd] = dateFormatTimeStamp(state.detailsPage.createTimeValue)
        const params = {
          channelId: state.detailsRows.id,
          datetimeStart, datetimeEnd,
          ...state.detailsPage,
          createTimeValue: null
        }
        const res = await fetchChannelTrading(params)
        if (res.code === 200) {
          const {list, total} = res.data
          state.detailsTableData = list.map(item => {
            item.tradingTime = item.tradingTime.slice(0, 10)
            return item
          })
          state.detailsPage.total = total
        }
      },

      async savePrice(row) {
        const res = await channelTradingEditUnitPrice({
          tradingId: row.tradingId,
          unitPrice: parseFloat(row.unitPrice)
        })
        if (res.code === 200) {
          state.priceKey = null
          methods.getTransactionDetails()
          ElMessage.success('修改成功')
        }
      },
      detailsPageClear() {
        state.priceKey = null
        state.detailsPage = {
          pageSize: 10,
          pageNum: 1,
          total: 0
        }
      },
      addChannelConfirm() {
        addChannelFormRef.value.validate(async v => {
          if (v) {
            const res = await addChannel(state.addChannelForm)
            if (res.code === 200) {
              ElMessage.success('添加成功')
              methods.getTableData()
              state.addChannelVisible = false
            }
          }
        })
      }
    }
    onMounted(() => {
      methods.getTableData()
      methods.getSelect()
    })
    return {
      detailsTableColumn,
      tableColumn,
      addChannelFormRef,
      uploadFileRef,
      addTransactionFormRef,
      ...methods,
      ...toRefs(state)
    }
  }
}
</script>

<style scoped>

</style>
